#include "user_cfg.h"
#include "sys_cfg_depend.h"
#include "plat_api.h"
#include "app_delay.h"


unsigned char __attribute__((aligned(8))) cfgbuf[CFG_SIZE];
CFG_TYPE *p_wcfg = (CFG_TYPE*)cfgbuf;
const  CFG_TYPE *p_readcfg = (const  CFG_TYPE*)&cfgbuf;
static unsigned char sid[6] = {0,};
static volatile unsigned int reboot_ticks = 0;

static void _cmm_restart(void) {						
	printf("%s\r\n", __func__);
    //NVIC_SystemReset();
	system("reboot");
    /*can't run here?*/
    while(1){sleep(1);}
}

static unsigned char _do_restart_tick(void) {
    unsigned char busy = 0;
	if(reboot_ticks != 0) {
        busy = 1;
		reboot_ticks--;
		if(reboot_ticks == 0)
			_cmm_restart();
	}
    return busy;
}

static void _checkWrite_usercfg_flash(void) {
    if(flash_flag != 0) {
        adt_flash_write(cfgbuf, sizeof(cfgbuf));
        flash_flag = 0;
    }
}

void user_reboot(unsigned char nsec) {
	if(reboot_ticks == 0) {
		reboot_ticks= MAX(2, nsec);
	}
}


void usercfg_set_default(void) {
    memset(cfgbuf, 0, sizeof(cfgbuf));
    p_wcfg->vol_JT = 80;
    p_wcfg->user_passw = 0;
    adt_flash_write(cfgbuf, sizeof(cfgbuf));
    printf("syscfg restore!\n");
}

const unsigned char* read_serid(void) {
    return (const unsigned char*)sid; 
}

int _serid_init(unsigned char *dsid, const unsigned short len) {
    int rlen, fd, ret = 0, i;
    if(len == 6) {
        const char* serid_filename = "dev/mtd1";
        unsigned char buf[12];
        fd= open(serid_filename, O_RDONLY);
        if(fd >= 0) {
            rlen = read(fd, buf, 12); 
            if(rlen == 12) {
                for(i = 0; i < 6; i++) {
                    sid[i] = nstar_cmm_canver_get_hex_dec_byte((unsigned char*)buf+ i*2);
                }
                ret = 1;
            }
        }
    }
    return ret;
}


void usercfg_init(void) {
    unsigned int size = sizeof(cfgbuf);
    int32_t len;
    adt_flash_init();
    _serid_init(sid, 6);
    len = adt_flash_read(cfgbuf, size);
    printf("read len is %d/%d\n", len ,size);
    if(len != size) {
        usercfg_set_default();
    }
}

void usercfg_handle_loop(void) {
    static volatile long app_tcnt = 0;   
    if( app_pend_wake(app_tcnt) ) {
        if(0 == _do_restart_tick()) {
            /*避免写flash时重启，特别是不可硬重启*/
            _checkWrite_usercfg_flash();
        }
        app_sleep(&app_tcnt, 1*1000);
    }
}




